//
//  ReplayTraceViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/29.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "ReplayTraceViewController.h"
#import "HandleView.h"
#import "MoveAnnotationView.h"
#import "TraceModel.h"

#define kStartTitle  @"start"
#define kDestiTitle  @"desti"
#define kRouteTitle  @"route"
#define kTimeInterval 0.5
#define kSpeedSliderMinValue 0.05
#define kSpeedSliderMaxValue 0.5

#define kSendModelNotification @"kSendModelNotification"

@interface ReplayTraceViewController ()<MAMapViewDelegate>
{
    CLLocationCoordinate2D *_traceCoordinate;
    
    NSUInteger _traceCount;

    /* 记录标注点的位置 */
    NSInteger _sliderIndex;
    
    UIButton *_btn;
}

@property (nonatomic, strong) HandleView *handleView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) MAPolyline *polyline;

@property (nonatomic, strong) TraceModel *movedAnnotation;

@property (nonatomic, strong) MoveAnnotationView *annotationView;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *endAnnotation;

@end

@implementation ReplayTraceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"轨迹回放";
    self.fd_interactivePopDisabled = true;
    // 创建MapView
    [self initMapView];
    // 初始化轨迹数据
    [self initTraceData];
    // 添加所有子控件
    [self setupSubviews];
    // 画出所有轨迹
    [self drawTraceLines];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

- (instancetype)init
{
    if (self = [super init])
    {
        [self initTimerOpen:NO interval:kTimeInterval];
    }
    return self;
}

- (void)initTimerOpen:(BOOL)open interval:(float)interval
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                  target:self selector:@selector(timerAction)
                                                userInfo:nil
                                                 repeats:YES];
    if (open) {
        self.timer.fireDate = [NSDate distantPast];
    } else {
        self.timer.fireDate = [NSDate distantFuture];
    }
}

- (void)setupSubviews
{
    [self setupButton];
    // handle view
    _handleView = [[HandleView alloc] init];
    _handleView.progrSlider.maximumValue = _traceCount-1;
    _handleView.speedSlider.minimumValue = kSpeedSliderMinValue;
    _handleView.speedSlider.maximumValue = kSpeedSliderMaxValue;
    _handleView.layer.shadowRadius = 2;
    _handleView.layer.shadowOpacity = 0.3;
    _handleView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    [self.view addSubview:_handleView];
    
    _handleView.sd_layout
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0)
    .bottomSpaceToView(self.view, 0)
    .heightIs(100);
    
    // map view
    self.mapView.sd_layout
    .topEqualToView(self.view)
    .bottomSpaceToView(_handleView, 0);
    self.mapView.delegate = self;
    self.mapView.zoomLevel = 13;
    self.mapView.showsUserLocation = NO;
    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    
    self.zoomBtnContainer.sd_layout
    .bottomSpaceToView(_handleView, 30);
    
    self.userLocBtn.sd_layout
    .autoWidthRatio(0);
    self.userLocBtn.hidden = YES;
    
    @weakify(self);
    _handleView.playBlock = ^(UIButton *btn) {
        @strongify(self);
        _btn = btn;
        [self playAction:btn];
    };
    
    _handleView.progrBlock = ^(NSInteger value) {
        @strongify(self);
        [self progressSlider:value];
    };
    
    _handleView.speedBlock = ^(CGFloat value) {
        @strongify(self);
        [self speedSlider:value];
    };
}

#pragma mark - progress slider -
- (void)progressSlider:(NSInteger)value
{
    _sliderIndex = value;
    _btn.selected = NO;
    
    [self setMapViewCenterCoordinate];
}

- (void)timerAction
{
    // 标注点结束
    if (_sliderIndex == _traceCount - 1) {
        _sliderIndex = 0;
        [self playAction:_btn];
        return;
    }
    _sliderIndex++;
    _handleView.progrSlider.value = _sliderIndex;
    [self.mapView setZoomLevel:17.5];
    [self setMapViewCenterCoordinate];
}

- (void)setMapViewCenterCoordinate
{
    [self.mapView setCenterCoordinate:_traceCoordinate[_sliderIndex]];
    [self.movedAnnotation setCoordinate:_traceCoordinate[_sliderIndex]];
    TraceModel *tModel = self.dataSource[_sliderIndex];
    tModel.ownerName = self.ownerName;
    self.annotationView.tModel = tModel;
}

#pragma mark - speed slider -
- (void)speedSlider:(CGFloat)value {
    
    CGFloat interval = (_handleView.speedSlider.minimumValue + _handleView.speedSlider.maximumValue) - value;
    [self.timer invalidate]; // 关闭
    
    if (_btn.selected) {
        [self initTimerOpen:YES interval:interval];
    } else {
        [self initTimerOpen:NO  interval:interval];
    }
}

#pragma mark - play action -
- (void)playAction:(UIButton *)btn
{
    btn.selected = !btn.selected;

    if (btn.selected) // 播放
    {
        [self.timer setFireDate:[NSDate distantPast]];
        _handleView.progrSlider.enabled = NO;
    }
    else // 暂停
    {
        [self.timer setFireDate:[NSDate distantFuture]];
        _handleView.progrSlider.enabled = YES;
    }
}

- (void)initTraceData
{
    _traceCount = self.dataSource.count;
    _traceCoordinate = (CLLocationCoordinate2D *)malloc(self.dataSource.count * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < _traceCount; i++) {
        TraceModel *tModel = [self.dataSource objectAtIndex:i];
        _traceCoordinate[i] = CLLocationCoordinate2DMake([tModel.gdLat doubleValue], [tModel.gdLng doubleValue]);
    }
}

- (void)drawTraceLines
{
    // 画出轨迹
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:_traceCoordinate count:_traceCount];

    [self.mapView addOverlay:polyline];
    [self.mapView showOverlays:self.mapView.overlays edgePadding:UIEdgeInsetsMake(100, 100, 100, 150) animated:YES];
    
    // 添加地图所需标注点
    [self addAnnotationToMap];
}

- (void)addAnnotationToMap {
    // 起始点
    self.startAnnotation = [[MAPointAnnotation alloc] init];
    self.startAnnotation.coordinate = _traceCoordinate[0];
    self.startAnnotation.title = kStartTitle;
    
    self.endAnnotation = [[MAPointAnnotation alloc] init];
    self.endAnnotation.coordinate = _traceCoordinate[_traceCount-1];
    self.endAnnotation.title = kDestiTitle;

    [self.mapView addAnnotations:@[self.startAnnotation,self.endAnnotation]];
    
    self.movedAnnotation = [[TraceModel alloc] init];
    self.movedAnnotation.title = @"movedAnnotation";
    self.movedAnnotation.coordinate = _traceCoordinate[0];
    [self.mapView addAnnotation:self.movedAnnotation];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    
    if([annotation isKindOfClass:[TraceModel class]])
    {
        static NSString *annotationIdentifier = @"movedAnnotationIdentifier";

        MoveAnnotationView *annotationView = (MoveAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];

        if (annotationView == nil)
        {
            annotationView = [[MoveAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
            annotationView.canShowCallout = NO;
            annotationView.displayType = DisplayTypeTrace;//轨迹回放
            [annotationView setSelected:YES];
            
            self.annotationView = annotationView;
        }
        
        TraceModel *tModel = self.dataSource.firstObject;
        tModel.ownerName = self.ownerName;
        self.annotationView.tModel = tModel;

        return annotationView;
        
    } else if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {//始末点
        static NSString *annotationIdentifier = @"lcoationIdentifier";
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];

        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
        }

        if ([annotation.title isEqualToString:kStartTitle])
        {
            annotationView.image = IMAGE_NAMED(@"trackingPoints");
        } else if ([annotation.title isEqualToString:kDestiTitle])
        {
            annotationView.image = IMAGE_NAMED(@"end_point");
            annotationView.centerOffset = CGPointMake(0, -16);
        }

        [self.annotationView.superview bringSubviewToFront:self.annotationView];
        
        return annotationView;
    }
    return nil;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *view = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        view.lineWidth = 4.0;
        view.strokeColor = kBaseColor;
        return view;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{
    if (view.annotation == self.movedAnnotation)
    {
        [mapView selectAnnotation:self.movedAnnotation animated:YES];
    }
}

- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray arrayWithArray:self.traces];
    }
    return _dataSource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
